﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace centraldba_dbrestore_utility
{
    public delegate void ConnectionSelectedHandler(object sender, ConnectionEventArgs e);

    /// <summary>
    /// Interaction logic for frmConnect.xaml
    /// </summary>
    public partial class frmConnect : Window
    {
        public event ConnectionSelectedHandler ConnectionSelected;

        public frmConnect()
        {
            InitializeComponent();

            // List any recent connections
            string sUserServers = centraldba_dbrestore_utility.Properties.Settings.Default.MySQLServers.ToString();
            if (!sUserServers.Length.Equals(0))
            {
                System.Xml.XmlDocument userServers = new System.Xml.XmlDocument();
                userServers.LoadXml(sUserServers);

                foreach (System.Xml.XmlNode xn in userServers.SelectNodes("/servers/server"))
                {
                    lstRecentConnections.Items.Add(xn.InnerText);
                }
            }

            // Set initial form focus
            txtServerName.Focus();
        }

        protected virtual void OnConnectionSelected(ConnectionEventArgs e)
        {
            if (ConnectionSelected != null)
                ConnectionSelected(this, e);
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            System.Xml.XmlElement xe;
            System.Xml.XmlNode rootNode;

            if (!txtServerName.Text.Trim().Length.Equals(0) && !lstDatabaseName.Text.Trim().Length.Equals(0))
            {
                string newServer = txtServerName.Text.Trim().ToUpper() + "." + lstDatabaseName.Text.Trim();
                string sUserServers = centraldba_dbrestore_utility.Properties.Settings.Default.MySQLServers.ToString();
                System.Xml.XmlDocument userServers = new System.Xml.XmlDocument();
                if (!sUserServers.Length.Equals(0)) userServers.LoadXml(sUserServers);

                // If this is the first document, create the root node
                if (userServers.SelectNodes("/servers").Count.Equals(0))
                {
                    xe = userServers.CreateElement("servers");
                    rootNode = userServers.AppendChild(xe);
                    xe = null;
                }
                else
                {
                    rootNode = userServers.SelectSingleNode("/servers");
                }

                // Determine if the connection entered already exists, if not add it
                if (!userServers.SelectNodes("/servers").Count.Equals(0))
                {
                    if (userServers.SelectNodes("/servers/server[server = '" + newServer + "']").Count.Equals(0))
                    {
                        xe = userServers.CreateElement("server");
                        xe.InnerText = newServer;
                        rootNode.AppendChild(xe);

                        centraldba_dbrestore_utility.Properties.Settings.Default.MySQLServers = userServers.OuterXml;
                        centraldba_dbrestore_utility.Properties.Settings.Default.Save();
                    }
                }

                userServers = null;
                rootNode = null;

                // Return the new database connection to the caller
                ConnectionEventArgs selectedConnection = new ConnectionEventArgs();
                selectedConnection.Connection = newServer;
                OnConnectionSelected(selectedConnection);
            }
            else if (lstRecentConnections.SelectedIndex >= 0)
            {
                // Return the selected database connection to the caller
                ConnectionEventArgs selectedConnection = new ConnectionEventArgs();
                selectedConnection.Connection = lstRecentConnections.SelectedValue.ToString();
                OnConnectionSelected(selectedConnection);
            }

            this.Close();
        }

        private void lstDatabaseName_DropDownOpened(object sender, EventArgs e)
        {
            // Clear the current list of databases
            if (lstDatabaseName.HasItems) lstDatabaseName.Items.Clear();

            // Get connection string template
            string conn = centraldba_dbrestore_utility.Properties.Settings.Default.ConnectionStringTemplate.ToString().Replace("centraldba_db", "master").Replace("yourserver", txtServerName.Text);

            // Get a list of current databases on the server
            System.Data.SqlClient.SqlConnection cn = null;
            System.Data.SqlClient.SqlCommand cm = null;
            System.Data.SqlClient.SqlDataReader dr = null;
            try
            {
                cn = new System.Data.SqlClient.SqlConnection(conn);
                cn.Open();
                cm = cn.CreateCommand();
                cm.CommandType = System.Data.CommandType.Text;
                cm.CommandText = "SELECT [name] FROM [sys].[databases] ORDER BY [name]";
                dr = cm.ExecuteReader(System.Data.CommandBehavior.SingleResult & System.Data.CommandBehavior.CloseConnection);
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        lstDatabaseName.Items.Add(dr.GetString(0));
                    }
                }
            }
            finally
            {
                if (dr != null)
                {
                    if (!dr.IsClosed) dr.Close();
                    dr = null;
                }
                if (cm != null)
                {
                    cm.Dispose();
                    cm = null;
                }
                if (cn != null)
                {
                    if (!cn.State.Equals(System.Data.ConnectionState.Closed)) cn.Close();
                    cn = null;
                }
            }
        }
    }
}
